/************************************************************************
* world.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"
#include "path.h"

#include "map.h"

#include <stdio.h>

/*
static struct {
} world_data = {
};
*/

static int world_create_new()
{
	char buff[2048];
	char name[256];
	int i;

	if (!path_get("worlds","new_world",1,buff,2048)) {
		if (!path_get("worlds","new_world",0,buff,2048))
			return 1;

		command_execf("set world.path %s",buff);
		command_execf("set world.name New World");

		return 0;
	}

	for (i=1; i<100; i++) {
		snprintf(name,256,"new_world_%d",i);
		if (!path_get("worlds",name,1,buff,2048)) {
			if (!path_get("worlds",name,0,buff,2048))
				return 1;

			command_execf("set world.path %s",buff);
			command_execf("set world.name New World %d",i);

			return 0;
		}
	}

	return 1;
}

static void world_clear_cfg()
{
	config_set("world.name",NULL);
	config_set("world.path",NULL);
	config_set("world.map.seed",NULL);
}

/* initialise and/or create a world */
int world_init(char* name)
{
	char buff[2048];

	world_clear_cfg();

	if (!name) {
		if (world_create_new())
			return 1;
	}else{
		if (str_sanitise(buff,2048,name) < 1)
			return 1;

		vlprintf(CN_INFO,"world: '%s' '%s'",name,buff);

		command_execf("set world.path %s",buff);
		command_execf("set world.name %s",name);
	}

	/* TODO: init environment before loading config, so that env commands work */

	if (path_get("world","world.cfg",1,buff,2048)) {
		config_load(buff);
	}else{
		/* TODO: setup world config from ui/config options */
		if (config_get("map.seed")) {
			int s = config_get_int("map.seed");
			config_set_int("world.map.seed",s);
		}
	}

	/* TODO: setup new/missing world config */

	if (!config_get("world.map.seed")) {
		int s = math_rand_range(-999999,999999);
		config_set_int("world.map.seed",s);
		mapgen_seed(s);
	}else{
		int s = config_get_int("world.map.seed");
		mapgen_seed(s);
	}

	/* TODO: add any server-side map triggers */

	map_init();

	return 0;
}

/* shutdown, save, clear, and free the current world */
void world_exit()
{
	map_exit();
	config_save("world","world","world.cfg");
	world_clear_cfg();
	map_trigger_clear();
}
